package com.live.dengdengtv.activity.login;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.live.dengdengtv.BaseActivity;
import com.live.dengdengtv.R;
import com.live.dengdengtv.activity.setting.AvatarActivity;
import com.live.dengdengtv.activity.setting.BindPhoneActivity;
import com.live.dengdengtv.activity.setting.EditInfoActivity;
import com.live.dengdengtv.bean.AppInfo;
import com.live.dengdengtv.bean.SimpleInfo;
import com.live.dengdengtv.kernel.EditActivity;
import com.live.dengdengtv.kernel.utils.SxbLog;
import com.live.dengdengtv.net.NetTaskList;
import com.live.dengdengtv.utils.Lo;
import com.live.dengdengtv.utils.Notice;
import com.live.dengdengtv.utils.ProvinceCity;
import com.live.dengdengtv.view.DialogWaiting;
import com.live.dengdengtv.widget.AddressPickerDialog;
import com.live.dengdengtv.widget.MaritalStatusDialog;
import com.live.dengdengtv.widget.WheelDatePickerDialog;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.request.RequestCall;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import okhttp3.Call;

public class PersonalInfoActivity extends BaseActivity implements View.OnClickListener{

    private static final String TAG = "PersonalInfoActivity";



    private final static int REQ_EDIT_AVATAR = 99;
    private final static int REQ_EDIT_NICKNAME = 100;
    private final static int REQ_EDIT_ID = 101;
    private final static int REQ_EDIT_SEX = 102;
    private final static int REQ_EDIT_SIGN = 103;
    private final static int REQ_EDIT_PHONE = 104;
    private final static int REQ_EDIT_ADRESS = 105;
    private final static int REQ_EDIT_AGE = 106;
    private final static int REQ_EDIT_MARITAL = 107;

    private Uri imageUrl;


    private ImageView avatar_iv;
    private TextView edit_nickName_tv;
    private TextView edit_id_tv;
    private TextView edit_sex_tv;
    private TextView edit_sign_tv;
    private TextView edit_phone_tv;
    private TextView edit_adrress_tv;
    private TextView edit_age_tv;
    private TextView edit_marital_tv;

    private ArrayList<String> marrayState;

    private String birthday;
    private ProvinceCity provinceCityUtil;
    private String provinceId = "";
    private String cityId = "";
    private RequestCall saveRequestCall;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {

            if(avatarFile.length() > 0){
                progressDialog.dimiss();
                saveRequestCall.execute(updateEditCallback);
            }else {
                handler.sendEmptyMessageDelayed(1,1000);
            }
            Lo.e("fileLength = "+ avatarFile.length());
        }
    };
    private File avatarFile;
    private DialogWaiting progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
        String display = "";
        if(null != intent){
            display = intent.getStringExtra("display");
        }

        if("red".equals(display)){
            setContentView(R.layout.activity_personalinfo_red);
            findViewById(R.id.title_right_tv).setOnClickListener(this);
        }else {
            setContentView(R.layout.activity_personalinfo_blue);
            setToolbar(true, R.string.skip, "完善资料");
        }

        initTitle();
        initView();
        initData();

//        String[] marrayState = new String[]{"保密","单身","恋爱中","已婚","同性"};
        marrayState = new ArrayList<String>();
        marrayState.add("保密");
        marrayState.add("单身");
        marrayState.add("恋爱中");
        marrayState.add("已婚");
        marrayState.add("同性");
    }

    private void initTitle() {
        ImageView title_left_iv = (ImageView) findViewById(R.id.title_left_iv);
        title_left_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        TextView title_center_tv = (TextView) findViewById(R.id.title_center_tv);
        title_center_tv.setText("编辑资料");

        TextView title_right_tv = (TextView) findViewById(R.id.title_right_tv);
        title_right_tv.setText("保存");
    }

    private void initView() {

        avatar_iv = (ImageView) findViewById(R.id.avatar_iv);
//        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.default_avatar);
//        Bitmap cirBitMap = UIUtils.createCircleImage(bitmap, 0);
//        avatar_iv.setImageBitmap(cirBitMap);

        avatar_iv.setOnClickListener(this);

        edit_nickName_tv = (TextView)findViewById(R.id.edit_nickName_tv);
        edit_nickName_tv.setOnClickListener(this);

        edit_id_tv = (TextView)findViewById(R.id.edit_id_tv);
        edit_id_tv.setOnClickListener(this);

        edit_sex_tv = (TextView)findViewById(R.id.edit_sex_tv);
        edit_sex_tv.setOnClickListener(this);

        edit_sign_tv = (TextView)findViewById(R.id.edit_sign_tv);
        edit_sign_tv.setOnClickListener(this);

        edit_phone_tv = (TextView)findViewById(R.id.edit_phone_tv);
        edit_phone_tv.setOnClickListener(this);

        edit_adrress_tv = (TextView)findViewById(R.id.edit_adrress_tv);
        edit_adrress_tv.setOnClickListener(this);

        edit_age_tv = (TextView)findViewById(R.id.edit_age_tv);
        edit_age_tv.setOnClickListener(this);

        edit_marital_tv = (TextView)findViewById(R.id.edit_marital_tv);
        edit_marital_tv.setOnClickListener(this);

//        ArrayList<HashMap<View,Integer>> editeViewList = new ArrayList<HashMap<View,Integer>>();

    }


    protected void initData() {

        edit_id_tv.setText(AppInfo.loginInfo.getUserId());
        String avatarAddress = AppInfo.loginInfo.getAvatarAddress();
        if(!TextUtils.isEmpty(avatarAddress)){
            //TODO:  需要改
//            Bitmap bitmap = BitmapFactory.decodeFile(AppInfo.loginInfo.getAvatarAddress());
//            avatar_iv.setImageBitmap(bitmap);

            if(avatarAddress.startsWith("http")){
                ImageLoader.getInstance().displayImage(avatarAddress, avatar_iv);
            }else {
                avatar_iv.setImageURI(Uri.fromFile(new File(avatarAddress)));
            }
        }


        if(TextUtils.isEmpty(AppInfo.loginInfo.getUserNickname())){
            //TODO:  需要改
            return;
        }
        edit_nickName_tv.setText(AppInfo.loginInfo.getUserNickname());

        String mSex = AppInfo.loginInfo.getUserSex();
        if("1".equals(mSex)){
            edit_sex_tv.setText("男");
        }else if("2".equals(mSex)){
            edit_sex_tv.setText("女");
        }else {
            edit_sex_tv.setText("保密");
        }

        edit_sign_tv.setText(AppInfo.loginInfo.getUserSign());
        edit_phone_tv.setText(AppInfo.loginInfo.getUserPhone());

        edit_adrress_tv.setText(AppInfo.loginInfo.getUserAdrress());
//        String provinceId = AppInfo.loginInfo.getUserProvinceId();
//        String cityId = AppInfo.loginInfo.getUserCityId();
//        String province = "";
//        String city = "";
//        provinceCityUtil = new ProvinceCity(this);
//        if(!TextUtils.isEmpty(provinceId)){
//            province = provinceCityUtil.getProvince(provinceId);
//            if(!TextUtils.isEmpty(cityId)){
//                city = provinceCityUtil.getCity(province, cityId);
//            }
//            edit_adrress_tv.setText(province + " " + city);
//        }

        if(!TextUtils.isEmpty(AppInfo.loginInfo.getUserAge())){
            edit_age_tv.setText(AppInfo.loginInfo.getUserAge());
        }else if(!TextUtils.isEmpty(AppInfo.loginInfo.getUserBirthday())){
            String birthday = AppInfo.loginInfo.getUserBirthday();
            SimpleDateFormat SDF = new SimpleDateFormat("yyyy", Locale.getDefault());
            try {
                Date data = SDF.parse(birthday);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(data);
                int age = WheelDatePickerDialog.getAge(calendar.get(Calendar.YEAR),
                        calendar.get(Calendar.MONTH) + 1,
                        calendar.get(Calendar.DAY_OF_MONTH));
                edit_age_tv.setText(age+"");
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        String mMarital = AppInfo.loginInfo.getUserMarital();
        if("0".equals(mMarital)){
            mMarital = "保密";
        }else if("1".equals(mMarital)){
            mMarital = "单身";
        }else if("2".equals(mMarital)){
            mMarital = "恋爱中";
        }else if("3".equals(mMarital)){
            mMarital = "已婚";
        }else if("4".equals(mMarital)){
            mMarital = "同性";
        }
        edit_marital_tv.setText(mMarital);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.title_right_tv:
                updateEdit();
                break;
            case R.id.avatar_iv:
                startActivityForResult(new Intent(context, AvatarActivity.class), REQ_EDIT_AVATAR);
                break;
            case R.id.edit_nickName_tv:
//                EditActivity.navToEdit(this, getString(R.string.profile_nickname), "", REQ_EDIT_NICKNAME);
                EditInfoActivity.startEditInfoActivity(this,EditInfoActivity.TYPE_TEXT,EditInfoActivity.BG_BLUE,"昵称",REQ_EDIT_NICKNAME);
                break;
            case R.id.edit_id_tv:
//                EditActivity.navToEdit(this, getString(R.string.profile_nickname), "", REQ_EDIT_ID);
                break;
            case R.id.edit_sex_tv:
//                EditActivity.navToEdit(this, "性别", "", REQ_EDIT_SEX);
                EditInfoActivity.startEditInfoActivity(this,EditInfoActivity.TYPE_SEX,EditInfoActivity.BG_BLUE,"性别",REQ_EDIT_SEX);
                break;
            case R.id.edit_sign_tv:
//                EditActivity.navToEdit(this, "个性签名", "", REQ_EDIT_SIGN);
                EditInfoActivity.startEditInfoActivity(this,EditInfoActivity.TYPE_SIGN,EditInfoActivity.BG_BLUE,"个性签名",REQ_EDIT_SIGN);
                break;
            case R.id.edit_phone_tv:
//                EditActivity.navToEdit(this, "手机号", "", REQ_EDIT_PHONE);
//                EditInfoActivity.startEditInfoActivity(this,EditInfoActivity.TYPE_TEXT,EditInfoActivity.BG_BLUE,"手机号",REQ_EDIT_PHONE);
                startActivityForResult(new Intent(context, BindPhoneActivity.class), REQ_EDIT_PHONE);
                break;
            case R.id.edit_adrress_tv:
//                EditActivity.navToEdit(this,"家乡", "", REQ_EDIT_ADRESS);
//                EditInfoActivity.startEditInfoActivity(this,EditInfoActivity.TYPE_TEXT,EditInfoActivity.BG_BLUE,"家乡",REQ_EDIT_ADRESS);

                new AddressPickerDialog().showDatePickerDialog(this, new AddressPickerDialog.OnWheelAddressDismiss() {
                    @Override
                    public void onWheelAddressDismiss(String p, String c,String pId,String cId) {
                        edit_adrress_tv.setText(p + " " + c);
//                        provinceId = provinceCityUtil.getProvincId(p);
//                        cityId = provinceCityUtil.getCityId(p, c);
//                        Lo.e(provinceId + " " +cityId);
                    }
                });
                break;

            case R.id.edit_age_tv:
//                EditActivity.navToEdit(this, "年龄", "", REQ_EDIT_AGE);
//                EditInfoActivity.startEditInfoActivity(this,EditInfoActivity.TYPE_TEXT,EditInfoActivity.BG_BLUE,"年龄",REQ_EDIT_AGE);
                new WheelDatePickerDialog().showDatePickerDialog(this, new WheelDatePickerDialog.OnWheelDateDismiss() {
                    @Override
                    public void onWheelDateDismiss(String age, String xingZuo, String date) {
                        edit_age_tv.setText(age+"，"+xingZuo);
                        birthday = date;
                    }
                });
                break;
            case R.id.edit_marital_tv:
//                EditActivity.navToEdit(this, "感情状况", "", REQ_EDIT_MARITAL);
//                EditInfoActivity.startEditInfoActivity(this,EditInfoActivity.TYPE_TEXT,EditInfoActivity.BG_BLUE,"感情状况",REQ_EDIT_MARITAL);
                int index = marrayState.indexOf(edit_marital_tv.getText().toString().trim());
                new MaritalStatusDialog().showPhotoDialog(this, index, new MaritalStatusDialog.OnItemSelected() {
                    @Override
                    public void onItemSelected(int selectIndex) {
                        edit_marital_tv.setText(marrayState.get(selectIndex));
                    }
                });
                break;

            default:
                break;
        }
    }



    private void updateEdit(){

        String sex = edit_sex_tv.getText().toString();
        if("男".equals(sex)){
            sex = "1";
        }else if("女".equals(sex)){
            sex = "2";
        }else {
            sex = "3";
        }

        int mState = marrayState.indexOf(edit_marital_tv.getText().toString().trim());
        if(mState == -1){
            mState = 0;
        }
        PostFormBuilder postFormBuilder = OkHttpUtils.post().url(NetTaskList.update_personalInfo)
                .addParams("token", AppInfo.TOKEN)
                .addParams("phone_type", AppInfo.PHONE_TYPE)
                .addParams("phone_system_version", AppInfo.getPhone_system_version())
                .addParams("phone_app_version", AppInfo.getPhone_app_version())
                .addParams("client_id", AppInfo.getClient_id())
                .addParams("user_id", AppInfo.loginInfo.getUserId())

                .addParams("birthday", TextUtils.isEmpty(birthday)? "":birthday)
//                .addParams("phone", edit_phone_tv.getText().toString())
                .addParams("nickname", edit_nickName_tv.getText().toString())
//                .addParams("sex", edit_sex_tv.getText().toString())
                .addParams("sex", sex)
                .addParams("self_description", edit_sign_tv.getText().toString())
                .addParams("emotion_type", mState+"")
                /*.addParams("city_id", cityId)
                .addParams("province_id", provinceId)*/;

        if(null != imageUrl && !TextUtils.isEmpty(imageUrl.getPath())){
            avatarFile = new File(imageUrl.getPath());
            Lo.e("fileLength = "+ avatarFile.length());
            postFormBuilder.addFile("upfile", avatarFile.getName(), avatarFile);
            saveRequestCall = postFormBuilder.build();
            progressDialog = DialogWaiting.show(context);
            handler.sendEmptyMessageDelayed(1,1000);
        }else {
            saveRequestCall = postFormBuilder.build();
            saveRequestCall.execute(updateEditCallback);
        }

    }

    private BaseInfoCallback updateEditCallback = new BaseInfoCallback(){

        public void onError(Call call, Exception e, int id) {
//            Notice.alert(context, "网络错误...");
            Notice.alert(context, e.getMessage());
            try {
                Lo.e("contentLength = "+call.request().body().contentLength());
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
        @Override
        public void onResponse(SimpleInfo response, int id) {

            try {
                Lo.e("contentLength = "+ saveRequestCall.getRequest().body().contentLength());
            } catch (IOException e) {
                e.printStackTrace();
            }

            if(response.result == 0){
                saveState();
                setResult(Activity.RESULT_OK);
                Notice.alertAndFinish(context,"修改成功!");
//                Notice.alert(context, response.data);

            }else {
                Notice.alert(context, "保存失败...");
            }
        }
    };

    private void saveState() {

        ArrayList<View> editViewList  = new ArrayList<View>();
        if(imageUrl!=null && !TextUtils.isEmpty(imageUrl.getPath())){
            avatar_iv.setTag(imageUrl.getPath());
        }

        editViewList.add(avatar_iv);
        editViewList.add(edit_nickName_tv);
        editViewList.add(edit_sex_tv);
        editViewList.add(edit_sign_tv);
        editViewList.add(edit_adrress_tv);
        editViewList.add(edit_age_tv);
        editViewList.add(edit_marital_tv);
        AppInfo.loginInfo.holdMyEdit(editViewList);
//        AppInfo.loginInfo.setUserProvinceId(provinceId);
//        AppInfo.loginInfo.setUserProvinceId(cityId);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK){
            SxbLog.e(TAG, "onActivityResult->failed for request: " + requestCode + "/" + resultCode);
            return;
        }
        Lo.e(data.getStringExtra(EditInfoActivity.RETURN_EXTRA));
        switch (requestCode){
            case REQ_EDIT_AVATAR:
                imageUrl = data.getData();
//                String imagePath = data.getStringExtra(AppConstants.RETURN_EXTRA_GENERAL);
                Bitmap bitmap = BitmapFactory.decodeFile(imageUrl.getPath());
//                Bitmap cirBitMap = UIUtils.createCircleImage(bitmap, 0);
                avatar_iv.setImageBitmap(bitmap);
                break;
            case REQ_EDIT_NICKNAME:
                edit_nickName_tv.setText(data.getStringExtra(EditInfoActivity.RETURN_EXTRA));
                break;
            case REQ_EDIT_ID:
//                edit_id_tv.setText(data.getStringExtra(EditActivity.RETURN_EXTRA));
//                break;
            case REQ_EDIT_SEX:
                edit_sex_tv.setText(data.getStringExtra(EditActivity.RETURN_EXTRA));
                break;
            case REQ_EDIT_SIGN:
                edit_sign_tv.setText(data.getStringExtra(EditActivity.RETURN_EXTRA));
                break;
            case REQ_EDIT_PHONE:
//                edit_phone_tv.setText(data.getStringExtra(EditActivity.RETURN_EXTRA));
                edit_phone_tv.setText("已绑定");
                break;
         }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //TODO  测试数字"100" 有什么用处
        MenuItem item = menu.add(Menu.NONE, Menu.FIRST, 100, "保存");
        item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        return super.onCreateOptionsMenu(menu);
    }

    @Override

    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == Menu.FIRST) {

//            TODO: 上传个人信息
            updateEdit();
            Intent intent = new Intent(context, RegisterActivity.class);
            startActivity(intent);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}















